package com.wjw.java.thread;

/**
 * 售票：线程不安全案例
 */
public class SellTicketUnsafe {
    public static void main(String[] args) {
        //useThread();
        useRunnable();
    }

    //1.使用继承Thread
    public static void useThread(){
        //三个售票窗口,开始售票
        TicketWindow1 window1 = new TicketWindow1();
        TicketWindow1 window2 = new TicketWindow1();
        TicketWindow1 window3 = new TicketWindow1();

        //当只剩下1张票时,会造成3个窗口都抢到了那张票,没有形成互斥关系(锁),
        //就会出现超卖现象
        window1.start();
        window2.start();
        window3.start();
    }

    //2.使用实现Runnable接口
    public static void useRunnable(){
        //三个售票窗口,开始售票
        TicketWindow2 window1 = new TicketWindow2();
        Thread t1 = new Thread(window1,"窗口1");//name给线程起名称
        Thread t2 = new Thread(window1,"窗口2");//name给线程起名称
        Thread t3 = new Thread(window1,"窗口3");//name给线程起名称

        //当只剩下1张票时,会造成3个窗口都抢到了那张票,没有形成互斥关系(锁),
        //就会出现超卖现象
        t1.start();
        t2.start();
        t3.start();
    }

}

//方式1：使用继承Thread类
class TicketWindow1 extends Thread{

    //使用static修饰,共享数据
    private static int ticketNum = 99;

    @Override
    public void run() {
       while (true){
           if(ticketNum <= 0){
               System.out.println("没票了,停止售票...");
               break;
           }
           String name = Thread.currentThread().getName();
           try {
               Thread.sleep(50);
               System.out.println("窗口："+ name +"售出一张票,剩余:"+ (-- ticketNum) +"张票..");
           } catch (InterruptedException e) {
               e.printStackTrace();
           }
       }
    }
}

//方式2：实现Runnable接口
class TicketWindow2 implements Runnable{

    //使用static修饰,共享数据
    private static int ticketNum = 99;

    @Override
    public void run() {
        while (true){
            if(ticketNum <= 0){
                System.out.println("没票了,停止售票...");
                break;
            }
            String name = Thread.currentThread().getName();
            try {
                Thread.sleep(50);
                System.out.println(name +"售出一张票,剩余:"+ (-- ticketNum) +"张票..");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}